package com.dxp.netty.server;

import com.dxp.netty.config.properties.NettyProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

/**
 * netty 启动类
 *
 * @author carzy
 * @date 2020/6/29
 */
@Component
public class NettyServer {

    private final NioEventLoopGroup boss;
    private final NioEventLoopGroup work;
    private final NettyProperties nettyProperties;
    private final Logger logger = LoggerFactory.getLogger(NettyServer.class);

    public NettyServer(NioEventLoopGroup boss, NioEventLoopGroup work, NettyProperties nettyProperties) {
        this.boss = boss;
        this.work = work;
        this.nettyProperties = nettyProperties;
    }

    @PostConstruct
    public void run() throws InterruptedException {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, work)
                // 指定Channel
                .channel(NioServerSocketChannel.class)
                //使用指定的端口设置套接字地址
                .localAddress(new InetSocketAddress(nettyProperties.getPort()))
                //服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数
                .option(ChannelOption.SO_BACKLOG, 1024)
                //设置TCP长连接,一般如果两个小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                //将小的数据包包装成更大的帧进行传送，提高网络的负载
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new NettyServerHandlerInitializer())
                .bind().sync()
                .addListener(future -> {
                    if (future.isSuccess()) {
                        logger.info("netty is running on port " + nettyProperties.getPort());
                    }
                });
    }

    @PreDestroy
    public void destroy() throws InterruptedException {
        boss.shutdownGracefully().sync();
        work.shutdownGracefully().sync();
        logger.info("destroy Netty");
    }

}
